package com.seu.vcampus.util;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 订单号生成工具类
 * 用于生成高并发下的唯一订单号
 * 订单号遵循规律：4位随机-当前时间（精确到秒）-序列号
 * 
 * @author 虚拟校园开发团队
 * @since 1.0.0
 */

public class IDGenerateUtil {
	private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
    private static final AtomicInteger COUNTER = new AtomicInteger(0);
    private static final int MAX_PER_MILLIS = 10000; //每毫秒最多生成1万个ID

    public static String generate() {
        String timestamp = LocalDateTime.now().format(FORMATTER);

        int count = COUNTER.getAndIncrement();
        if (count >= MAX_PER_MILLIS) {
            COUNTER.set(0);
            count = COUNTER.getAndIncrement();
        }

        //保证序列号固定宽度（4位）
        String sequence = String.format("%04d", count);
        
        int prefix = 1000 + ThreadLocalRandom.current().nextInt(9000);

        return prefix + timestamp + sequence;
    }
}
